package com.example.demosecurity.common.security;

import com.alibaba.fastjson2.JSON;
import com.example.demosecurity.common.utils.DataResult;
import com.example.demosecurity.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 自定义成功后处理
 */
@Component
public class CustomHandle implements AuthenticationSuccessHandler {
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public StringRedisTemplate stringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        return this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        User user = (User)authentication.getPrincipal();
        stringRedisTemplate.opsForValue().set("ms:user:token:"+authentication.getName(),JSON.toJSONString(user),1200, TimeUnit.SECONDS);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(JSON.toJSONString(DataResult.success("登录成功")));
    }
}
